package com.zee.admin.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zee.admin.dao.SysDictDataDao;
import com.zee.admin.dao.SysDictTypeDao;
import com.zee.admin.entity.SysDictType;
import com.zee.admin.model.dto.SysDictTypeQueryDTO;
import com.zee.admin.model.vo.DictDataVO;
import com.zee.admin.model.vo.DictTypeVO;
import com.zee.admin.service.ISysDictTypeService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;

@Service
public class SysDictTypeServiceImpl extends ServiceImpl<SysDictTypeDao, SysDictType> implements ISysDictTypeService {
    @Autowired
    private SysDictDataDao sysDictDataDao;

    @Override
    public Page<SysDictType> page(SysDictTypeQueryDTO dto) {
        Map<String, Object> params = BeanUtil.beanToMap(dto);
        return baseMapper.selectPage(new Page<>(dto.getPage(), dto.getPageSize()), getWrapper(params));
    }

    private LambdaQueryWrapper<SysDictType> getWrapper(Map<String, Object> params) {
        String dictType = (String) params.get("dictType");
        String dictName = (String) params.get("dictName");

        LambdaQueryWrapper<SysDictType> wrapper = new LambdaQueryWrapper<>();
        wrapper.like(StringUtils.isNotBlank(dictType), SysDictType::getDictType, dictType);
        wrapper.like(StringUtils.isNotBlank(dictName), SysDictType::getDictName, dictName);
        wrapper.orderByAsc(SysDictType::getSort);
        return wrapper;
    }

    @Override
    public List<DictTypeVO> getAllList() {
        List<DictTypeVO> typeList = baseMapper.getDictTypeList();
        List<DictDataVO> dataList = sysDictDataDao.getDictDataList();
        for (DictTypeVO type : typeList) {
            for (DictDataVO data : dataList) {
                if (type.getId().equals(data.getDictTypeId())) {
                    type.getDataList().add(data);
                }
            }
        }
        return typeList;
    }

}